#include <string.h>
#include "gpio-sysfs.h"
#include "io-infos.h"

extern "C" void orayio_setval_impl(int gpio, int val)
{
	gpio_export(gpio);
	gpio_set_dir(gpio, 1);
	gpio_set_value(gpio, val);
	return;
}

//这里用C链接
extern "C" void orayio_setval(const char *groups, int val)
{
	int grpnum;
	IO_GROUPS *pgroup = get_io_groups(grpnum);
	if (!pgroup)
		return;

	for (int pindex = 0; pindex < grpnum; pindex++) {
		IO_GROUPS &grp = pgroup[pindex];
		if (!strcmp(groups, grp.names)) {
			for (int i = 0; i < grp.size; i++) {
				int num = grp.infos[i].ionum;
				int posval = grp.infos[i].positive_val;
				gpio_export(num);
				gpio_set_dir(num, 1);
				gpio_set_value(num, val ? posval : !posval);
			}
			return;
		}
	}
}

extern "C" int orayio_get_input_val(const char *groups)
{
	int grpnum;
	IO_GROUPS *pgroup = get_io_groups(grpnum);
	if (!pgroup)
		return -1;

	for (int pindex = 0; pindex < grpnum; pindex++) {
		IO_GROUPS &grp = pgroup[pindex];
		if (!strcmp(groups, grp.names)) {
			for (int i = 0; i < grp.size; i++) {
				int num = grp.infos[i].ionum;
				int posval = grp.infos[i].positive_val;
				/* gpio_export(num); */
				unsigned int outval;
				if (0 == gpio_get_value(num, &outval)) {
					//有一个引脚不等于激活值 返回0
					if(outval != posval) {
						return 0;
					}
				} else {
					return -2;
				}
			}
			return 1;
		}
	}
	return -3;
}

extern "C" int orayio_get_output_val(const char *groups, int val)
{
	int grpnum;
	IO_GROUPS *pgroup = get_io_groups(grpnum);
	if (!pgroup)
		return -1;

	for (int pindex = 0; pindex < grpnum; pindex++) {
		IO_GROUPS &grp = pgroup[pindex];
		if (!strcmp(groups, grp.names)) {
			for (int i = 0; i < grp.size; i++) {
				int num = grp.infos[i].ionum;
				int posval = grp.infos[i].positive_val;
				gpio_export(num);
				gpio_set_dir(num, 0);
				/* gpio_set_dir(num, 1); */
				unsigned int outval;
				if (0 == gpio_get_value(num, &outval)) {
					//有一个引脚不等于激活值 返回0
					/* printf("outval posval:[%d, %d]\n", outval, posval); */
					if(outval != posval) {
						return 0;
					}
				} else {
					return -2;
				}
			}
			return 1;
		}
	}
	return -3;
}
